package com.halixun.d2app.ui.fragment;


import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.halixun.d2app.R;
import com.halixun.d2app.adapter.QingDanAdapter;
import com.halixun.d2app.base.BaseFragment;
import com.halixun.d2app.base.BaseResult;
import com.halixun.d2app.bean.QingDanInfo;
import com.halixun.d2app.net.CreateRequestEntity;
import com.halixun.d2app.net.errer.ResultVerifier;
import com.halixun.d2app.printer.PrinterUtils;
import com.halixun.d2app.utils.DataOperationUtil;
import com.halixun.d2app.utils.DensityUtil;
import com.halixun.d2app.utils.PrintReceiptsUtil;
import com.halixun.d2app.utils.RequestDataUtils;
import com.halixun.d2app.utils.RunningWaterUtil;
import com.halixun.d2app.utils.SystemUtil;
import com.halixun.d2app.utils.ToastUtils;
import com.halixun.d2app.utils.VersionUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class CommonFragment extends BaseFragment implements View.OnClickListener {

    private static final String KEY_TAG = "key_tag";

    private TextView reconstructionTime;

    private TimePickerView pvTime;

    private TextView pickerTimeView;

    private RecyclerView mRecyclerView;

    private Date mDate;

    private List<QingDanInfo> mQingDanInfos;

    private QingDanAdapter mAdapter;

    private TextView heji;

    private View noData;

    public static BaseFragment getInstance(String tag) {
        CommonFragment f = new CommonFragment();
        Bundle params = new Bundle();
        params.putString(KEY_TAG, tag);
        f.setArguments(params);
        return f;
    }

    private String tag;

    public CommonFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tag = getArguments().getString(KEY_TAG);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_common, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        setAdapter();
        getData();
    }

    private void setAdapter() {
        mQingDanInfos = new ArrayList<>();
        mAdapter = new QingDanAdapter(mQingDanInfos);
        mRecyclerView.setAdapter(mAdapter);
    }

    @SuppressLint("NewApi")
    private void getData() {
        CreateRequestEntity.getWebService().GetFoodSalesReport(RequestDataUtils.getRequestDataParam(mContext)).enqueue(new Callback<BaseResult<List<QingDanInfo>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<QingDanInfo>>> call, Response<BaseResult<List<QingDanInfo>>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    mQingDanInfos.clear();
                    mQingDanInfos.addAll(response.body().Data);
                    mAdapter.notifyDataSetChanged();
                    heji.setVisibility(mQingDanInfos.size() > 0 ? View.VISIBLE : View.GONE);
                    if (heji.getVisibility() == View.VISIBLE) {
                        double tPrice = 0;
                        for (QingDanInfo info : mQingDanInfos) {
                            tPrice = DataOperationUtil.add(tPrice, info.getSaleMoney());
                        }
                        heji.setText("合计：￥" + tPrice);
                    }
                } else {
                    ResultVerifier.serceErrers(response);
                }
                noData.setVisibility(mQingDanInfos.size() > 0 ? View.GONE : View.VISIBLE);
            }

            @Override
            public void onFailure(Call<BaseResult<List<QingDanInfo>>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
            }
        });
    }

    private void initData() {
        reconstructionTime.setText("重建时间(" + PrintReceiptsUtil.getResetTime() + ")");
    }

    @Override
    protected void initView() {
        reconstructionTime = mRootView.findViewById(R.id.reconstructionTime);
        mRecyclerView = mRootView.findViewById(R.id.mRecyclerView);
        heji = mRootView.findViewById(R.id.heji);
        noData = mRootView.findViewById(R.id.noData);
    }

    @Override
    protected void setListeners() {
        reconstructionTime.setOnClickListener(this);
        mRootView.findViewById(R.id.reconstructionWater).setOnClickListener(this);
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = DensityUtil.dp2px(mContext, (float) 0.5);
            }
        });

        mRootView.findViewById(R.id.printOrder).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.reconstructionTime:
                showTimeDialog();
                break;
            case R.id.reconstructionWater:
                RunningWaterUtil.resetRunningWate();
                ToastUtils.showCenterToast("重建成功");
                break;
            case R.id.printOrder:
                if (mQingDanInfos.size() == 0) return;
                PrinterUtils.printOrder(mQingDanInfos);
                break;
        }
    }


    private void showTimeDialog() {
        if (null == pvTime) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            pvTime = new TimePickerBuilder(mContext, null)
                    .setType(new boolean[]{false, false, false, true, true, false})
                    .setSubmitColor(getResources().getColor(R.color.commot_color))
                    .setCancelColor(getResources().getColor(R.color.commot_color))
                    .setLayoutRes(R.layout.select_pickerview_layout, new CustomListener() {
                        @Override
                        public void customLayout(View v) {
                            pickerTimeView = v.findViewById(R.id.pickerTime);
                            v.findViewById(R.id.pickerCancel).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (null != pvTime) {
                                        pvTime.dismiss();
                                    }
                                }
                            });
                            v.findViewById(R.id.pickerConfirm).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (null == mDate) {
                                        ToastUtils.showBottomToast("请选择重置时间");
                                        return;
                                    }
                                    reconstructionTime.setText("重建时间(" + PrintReceiptsUtil.setResetTime(mDate) + ")");
                                    if (null != pvTime) {
                                        pvTime.dismiss();
                                    }
                                }
                            });
                        }
                    })
                    .setTimeSelectChangeListener(date -> {
                        this.mDate = date;
                        if (null != pickerTimeView) {
                            pickerTimeView.setText(new SimpleDateFormat("HH:mm", Locale.getDefault()).format(date));
                        }
                    })
                    .setContentTextSize(10)
                    .isDialog(true)
                    .setTextColorCenter(Color.parseColor("#FF4B01"))
                    .setTextColorOut(Color.parseColor("#aaaaaa"))
                    .setDate(calendar)
                    .setOutSideCancelable(false)
                    .build();
        }
        pvTime.show();
    }
}
